package cn.migu.music.hangupsms.cachemanage.handler;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import cn.migu.music.common.utils.LogUtils;
import cn.migu.music.hangupsms.cachemanage.event.AbsCacheEvent;
import cn.migu.music.hangupsms.cachemanage.event.EventConstants;
import cn.migu.music.hangupsms.common.config.HangUpSmsDbConfig;
import cn.migu.music.hangupsms.common.entity.SmsTemplateSettings;
import cn.migu.music.hangupsms.repository.SmsTemplateSettingsMapper;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
@EqualsAndHashCode(callSuper = true)
public class SmsTemplateCacheHandler extends AbsCacheHandler<AbsCacheEvent>{
    @Autowired
    private SmsTemplateSettingsMapper smsTemplateSettingsMapper;
    @Autowired
    private HangUpSmsDbConfig         hangUpSmsDbConfig;

    @PostConstruct
    @Override
    public void init() {
        reload(EventConstants.SMS_TEMPLATE_CHANGED_EVNET);
    }

    @Override public void reload(AbsCacheEvent cacheEvent) {
        List<SmsTemplateSettings> templateSettingsList = null;
        try {
            templateSettingsList = smsTemplateSettingsMapper.getAllSettings();
        } catch (Exception e) {
            LogUtils.error(e, log, "get data error");
        }
        if(CollectionUtils.isEmpty(templateSettingsList)){
            return;
        }
        Map<String,String> templateMap = new HashMap<>(templateSettingsList.size());
        for(SmsTemplateSettings settings: templateSettingsList){
            if(settings.getApplyStatus() == null ||settings.getApplyStatus() == 0){
                continue;
            }
            String templateId = settings.getTemplateId();
            String templateContent = settings.getTemplateContent();
            templateMap.put(templateId, templateContent);
        }
        hangUpSmsDbConfig.setMsgTemplateMap(templateMap);
    }
}
